import '../css/styles.css';

let softwareList = [];

// 将需要在 HTML 中调用的函数挂载到 window 对象
window.editSoftware = editSoftware;
window.showAuthorizePanel = showAuthorizePanel;
window.deleteSoftware = deleteSoftware;
window.saveEdit = saveEdit;
window.cancelEdit = cancelEdit;
window.closeAuthorizePanel = closeAuthorizePanel;
window.saveAuthorization = saveAuthorization;

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    const user = JSON.parse(localStorage.getItem('user'));
    if (!user || user.role !== 'admin') {
        window.location.href = 'login.html';
        return;
    }
    loadSoftwareList();
});

// 加载软件列表 
function loadSoftwareList() {
    fetch(getApiUrl('softwareList'), {
        headers: getAuthHeaders()
    })
        .then(response => {
            if (!response.ok) {
                if (response.status === 401 || response.status === 403) {
                    // 未认证或无权限时重定向到登录页面
                    window.location.href = 'login.html';
                    return;
                }
                throw new Error('获取列表失败');
            }
            return response.json();
        })
        .then(data => {
            console.log('获取到的软件列表:', data);
            softwareList = data;
            updateSoftwareList();
        })
        .catch(error => {
            console.error('获取软件列表失败:', error);
            showAlert('获取软件列表失败', 'error');
        });
}

// 格式化日期时间
function formatDateTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 更新软件列表显示
function updateSoftwareList() {
    const tbody = document.getElementById('softwareList');
    tbody.innerHTML = '';
    
    softwareList.forEach(software => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${software.name}</td>
            <td>${software.version}</td>
            <td>${software.description || ''}</td>
            <td>${formatDateTime(software.uploadTime)}</td>
            <td>
                <div class="action-buttons">
                    <button class="edit" onclick="editSoftware(${software.id})">编辑</button>
                    <button class="authorize" onclick="showAuthorizePanel(${software.id})">授权</button>
                    <button class="delete" onclick="deleteSoftware(${software.id})">删除</button>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 显示提示的函数
function showAlert(message, type) {
    const alertBox = document.getElementById('alertBox');
    if (!alertBox) {
        console.error('未找到 alertBox 元素');
        return;
    }
    
    alertBox.textContent = message;
    alertBox.className = `alert alert-${type}`;
    alertBox.style.display = 'block';
    
    setTimeout(() => {
        alertBox.style.animation = 'fadeOut 0.5s';
        setTimeout(() => {
            alertBox.style.display = 'none';
            alertBox.style.animation = '';
        }, 500);
    }, 3000);
}

// 编辑软件
function editSoftware(id) {
    const software = softwareList.find(s => s.id === id);
    if (!software) {
        showAlert('软件不存在', 'error');
        return;
    }

    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.className = 'overlay';
    overlay.addEventListener('click', cancelEdit);
    document.body.appendChild(overlay);

    // 创建编辑面板
    const editPanel = document.createElement('div');
    editPanel.className = 'edit-panel';
    editPanel.innerHTML = `
        <div class="edit-panel-header">
            <h3>编辑软件信息</h3>
            <button class="close-button" onclick="cancelEdit()">&times;</button>
        </div>
        <div class="form-group">
            <label>软件名称</label>
            <input type="text" id="editName" value="${software.name}" required>
        </div>
        <div class="form-group">
            <label>版本号</label>
            <input type="text" id="editVersion" value="${software.version}" required 
                   placeholder="例如：1.0.0 或 v1.0.0">
            <small>版本号格式：主版本号.次版本号.修订号</small>
        </div>
        <div class="form-group">
            <label>可执行文件名</label>
            <input type="text" id="editExeName" value="${software.exeName || ''}" 
                   placeholder="例如：app.exe">
            <small>软件的主程序文件名，例如：app.exe</small>
        </div>
        <div class="form-group">
            <label>描述</label>
            <textarea id="editDescription" rows="4">${software.description || ''}</textarea>
        </div>
        <div class="form-group">
            <label>当前软件包</label>
            <div class="static-text">${software.filename}</div>
        </div>
        <div class="form-group">
            <label>更新软件包</label>
            <input type="file" id="editPackage">
            <small>如果需要更新软件包，请选择新文件</small>
        </div>
        <div id="uploadProgress" style="display: none;">
            <progress value="0" max="100" style="width: 100%;"></progress>
            <div class="progress-text">上传进度：0%</div>
        </div>
        <div class="form-group">
            <label>上传时间</label>
            <div class="static-text">${formatDateTime(software.uploadTime)}</div>
        </div>
        <div class="edit-panel-buttons">
            <button class="secondary" onclick="cancelEdit()">取消</button>
            <button onclick="saveEdit(${software.id})">保存</button>
        </div>
    `;

    // 阻止点击面板本身时关闭
    editPanel.addEventListener('click', (e) => {
        e.stopPropagation();
    });

    document.body.appendChild(editPanel);

    // 添加动画效果
    requestAnimationFrame(() => {
        overlay.classList.add('active');
        editPanel.classList.add('active');
    });

    // 添加 ESC 键关闭功能
    const handleEscKey = (e) => {
        if (e.key === 'Escape') {
            cancelEdit();
            document.removeEventListener('keydown', handleEscKey);
        }
    };
    document.addEventListener('keydown', handleEscKey);
}

// 取消编辑
function cancelEdit() {
    const overlay = document.querySelector('.overlay');
    const editPanel = document.querySelector('.edit-panel');
    
    if (overlay && editPanel) {
        // 添加关闭动画
        overlay.classList.remove('active');
        editPanel.classList.remove('active');
        
        // 等待���画完成后移除元素
        setTimeout(() => {
            overlay.remove();
            editPanel.remove();
        }, 300);
    }
}

// 保存编辑
async function saveEdit(id) {
    const name = document.getElementById('editName').value;
    const version = document.getElementById('editVersion').value;
    const description = document.getElementById('editDescription').value;
    const exeName = document.getElementById('editExeName').value;
    const packageFile = document.getElementById('editPackage').files[0];

    if (!name || !version) {
        showAlert('请填写必要信息', 'error');
        return;
    }

    try {
        let updatedSoftware = { name, version, description, exeName };

        // 如果选择了新的软件包，先上传文件
        if (packageFile) {
            const progressBar = document.querySelector('#uploadProgress progress');
            const progressText = document.querySelector('.progress-text');
            document.getElementById('uploadProgress').style.display = 'block';

            const chunkSize = 1024 * 1024; // 1MB 分块
            const totalChunks = Math.ceil(packageFile.size / chunkSize);
            const identifier = Date.now().toString();

            // 上传所有分块
            for (let i = 0; i < totalChunks; i++) {
                const chunk = packageFile.slice(i * chunkSize, (i + 1) * chunkSize);
                const formData = new FormData();
                formData.append('chunk', chunk);

                const token = localStorage.getItem('token');
                const response = await fetch(getApiUrl('uploadChunk'), {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'X-Chunk-Index': i.toString(),
                        'X-Total-Chunks': totalChunks.toString(),
                        'X-Identifier': identifier,
                        'X-Filename': btoa(encodeURIComponent(packageFile.name)),
                        'X-Software-Name': btoa(encodeURIComponent(name)),
                        'X-Version': btoa(encodeURIComponent(version)),
                        'X-Description': btoa(encodeURIComponent(description || '')),
                        'X-Exe-Name': btoa(encodeURIComponent(exeName || '')),
                        'X-Update-Software-Id': id.toString()
                    },
                    body: formData
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '文件上传失败');
                }

                // 更新进度
                const progress = ((i + 1) / totalChunks) * 100;
                progressBar.value = progress;
                progressText.textContent = `上传进度：${progress.toFixed(1)}%`;

                const result = await response.json();
                if (result.software) {
                    updatedSoftware = result.software;
                }
            }
        } else {
            // 如果没有选择新文件，只更新基本信息
            const response = await fetch(`${config.baseUrl}/software/${id}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedSoftware)
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '更新失败');
            }

            const result = await response.json();
            updatedSoftware = result.software;
        }

        // 更新本地列表
        const index = softwareList.findIndex(s => s.id === id);
        if (index !== -1) {
            softwareList[index] = updatedSoftware;
            updateSoftwareList();
        }

        showAlert('软件信息更新成功', 'success');
        cancelEdit();
    } catch (error) {
        console.error('更新错误:', error);
        showAlert(error.message || '更新失败，请重试', 'error');
        document.getElementById('uploadProgress').style.display = 'none';
    }
}

// 删除软件
async function deleteSoftware(id) {
    if (!confirm('确定要删除这个软件吗？')) {
        return;
    }

    try {
        const response = await fetch(`${config.baseUrl}/software/${id}`, {
            method: 'DELETE',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            throw new Error('删除失败');
        }

        // 从本地列表中移除
        softwareList = softwareList.filter(s => s.id !== id);
        updateSoftwareList();
        showAlert('软件删除成功', 'success');
    } catch (error) {
        console.error('删除错误:', error);
        showAlert('删除失败，请重试', 'error');
    }
}

// 显示授权管理面板
function showAuthorizePanel(id) {
    const software = softwareList.find(s => s.id === id);
    if (!software) {
        showAlert('软件不存在', 'error');
        return;
    }

    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.className = 'overlay';
    overlay.addEventListener('click', closeAuthorizePanel);
    document.body.appendChild(overlay);

    // 获取用户列表
    fetch(getApiUrl('users'))
        .then(response => response.json())
        .then(users => {
            // 创建授权面板
            const panel = document.createElement('div');
            panel.className = 'edit-panel';
            panel.innerHTML = `
                <div class="edit-panel-header">
                    <h3>管理软件授权 - ${software.name}</h3>
                    <button class="close-button" onclick="closeAuthorizePanel()">&times;</button>
                </div>
                <div class="form-group">
                    <label>授权用户</label>
                    <div class="user-list">
                        ${users.map(user => `
                            <div class="user-item">
                                <label>
                                    <input type="checkbox" 
                                           value="${user.id}" 
                                           ${software.authorizedUsers?.includes(user.id) ? 'checked' : ''}>
                                    ${user.username} (${user.role})
                                </label>
                            </div>
                        `).join('')}
                    </div>
                </div>
                <div class="edit-panel-buttons">
                    <button class="secondary" onclick="closeAuthorizePanel()">取消</button>
                    <button onclick="saveAuthorization(${software.id})">保存</button>
                </div>
            `;

            panel.addEventListener('click', (e) => e.stopPropagation());
            document.body.appendChild(panel);

            requestAnimationFrame(() => {
                overlay.classList.add('active');
                panel.classList.add('active');
            });
        })
        .catch(error => {
            console.error('获取用户列表失败:', error);
            showAlert('获取用户列表失败', 'error');
        });
}

// 保存授权设置
async function saveAuthorization(id) {
    const checkboxes = document.querySelectorAll('.user-list input[type="checkbox"]:checked');
    const userIds = Array.from(checkboxes).map(cb => parseInt(cb.value));

    try {
        const response = await fetch(`${getApiUrl('software')}/${id}/authorize`, {
            method: 'PUT',
            headers: getAuthHeaders(),
            body: JSON.stringify({ userIds })
        });

        if (!response.ok) {
            throw new Error('更新授权失败');
        }

        const result = await response.json();
        
        // 更新本地列表
        const index = softwareList.findIndex(s => s.id === id);
        if (index !== -1) {
            softwareList[index] = result.software;
            updateSoftwareList();
        }

        showAlert('授权更新成功', 'success');
        closeAuthorizePanel();
    } catch (error) {
        console.error('授权更新错误:', error);
        showAlert('授权更新失败，请重试', 'error');
    }
}

// 关闭授权面板
function closeAuthorizePanel() {
    const overlay = document.querySelector('.overlay');
    const panel = document.querySelector('.edit-panel');
    
    if (overlay && panel) {
        overlay.classList.remove('active');
        panel.classList.remove('active');
        
        setTimeout(() => {
            overlay.remove();
            panel.remove();
        }, 300);
    }
}

// 在发送请求时添加认证头
function getAuthHeaders() {
    const token = localStorage.getItem('token');
    return {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    };
} 